<template>
	<view class="class_share">
		<view class="share-popup" v-if="isShowShare">
			<canvas canvas-id="posterCanvas" style="width: 100%; height:100vh"></canvas>
		</view>
		<view class="content">
			<view class="share_way_list">
				<!-- #ifdef H5 || APP-PLUS -->
				<view class="weixinBtn">
					<view @click="choseShareWay(item.type)" class="share_way" v-for="item in shareWay" :key="item.type">
						<image class="share_icon" :src="item.url"></image>
						<view class="share_tip">{{ item.tip }}</view>
					</view>
				</view>
				<!-- #endif -->

				<!-- #ifdef MP-WEIXIN -->
				<view class="weixinBtn">
					<view class="share_way" @click="savePoster()">
						<image class="share_icon" src="../static/images/class_share/save_ad.png"></image>
						<view class="share_tip">保存海报</view>
					</view>
					<button open-type="share" class="share_way share_btn">
						<image class="share_icon" src="../static/images/class_share/wechat.png"></image>
						<view open-type="share" class="share_tip">微信好友</view>
					</button>
					<view class="share_way" @click="shareToTimeline()">
						<image class="share_icon" src="../static/images/class_share/circle_of_friends.png"></image>
						<view class="share_tip">朋友圈</view>
					</view>
					<view class="share_way" @click="copy()">
						<image class="share_icon" src="../static/images/class_share/copy_link.png"></image>
						<view class="share_tip">复制链接</view>
					</view>
				</view>
				<!-- #endif -->
			</view>

		</view>
	</view>
</template>


<script>
	import {
		generate,
		shareDetail
	} from '@/api/promotion';
	export default {
		data() {
			return {
				shareWay: [{
						type: 1,
						url: require('@/static/images/class_share/save_ad.png'),
						tip: '保存海报'
					},
					{
						type: 2,
						url: require('@/static/images/class_share/wechat.png'),
						tip: '微信好友'
					},
					{
						type: 3,
						url: require('@/static/images/class_share/circle_of_friends.png'),
						tip: '朋友圈'
					},
					{
						type: 4,
						url: require('@/static/images/class_share/copy_link.png'),
						tip: '复制链接'
					},
				],
				screenWidth: 100,
				screenHeight: 100,
				imageUrl: "", //这是要保存的图片
				isShowShare: true,

				detailData: [],
				name: '',
				generaId: {},
				type: '',
			};
		},
		async onLoad(optin) {
			this.type = optin.type
		},
		onShow() {
			this.generate();
			// this.drawPoster();
		},
		methods: {
			//生成分享海报
			generate() {
				return new Promise((reject) => {
					generate({
							type: this.type,
							source_id: 1,
							jump_url: 'https://example.com/share',
						})
						.then(res => {
							this.generaId = res;
							this.getdetail()
							// console.log(res);
						})
						.catch(error => {
							console.error('请求失败:', error);
						});
				})
			},

			// 获取拼团海报详情
			getdetail() {
				// 调用后端接口获取拼团海报详情
				const params = {
					record_id: this.generaId.record_id,
					invite_code: this.generaId.invite_code
				}
				shareDetail(params).then((res) => {
					this.detailData = res;
					this.name = this.detailData.user.nickname.substring(0, 2);
					console.log('调用后端接口获取拼团海报详情', this.detailData)
					this.drawPoster();
				}).catch(() => {
					console.error();
				})

			},

			async drawPoster() {
				const resScreen = uni.getSystemInfoSync();
				// 获取当前设备的宽度 高度 单位为px
				this.screenWidth = resScreen.screenWidth;
				this.screenHeight = resScreen.screenHeight;
				// 绘画盒子的宽度  高度  单位rpx
				// const boxWidth = 800;
				// const boxHeight = 800;

				// 获取canvas上下文对象
				// const pxRatio = screenWidth / 700;　　　　
				// const width = boxWidth * pxRatio;　　　　// canvas宽度
				// const height = boxHeight * pxRatio *2;  // canvas高度
				const canvasBox = uni.createCanvasContext('posterCanvas', this, this.screenWidth, this.screenHeight);
				// 绘制当前图片
				uni.getImageInfo({
					src: this.detailData.record.qrcode_url,
					success: (res) => {
						const imgWidth = res.width; // 原始图片宽度
						const imgHeight = res.height; // 原始图片高度
						const targetWidth = 380; // 目标宽度
						// 根据目标高度计算等比例的宽度
						// const targetHeight = Math.floor((imgHeight / imgWidth) * targetWidth);
						canvasBox.drawImage('/static/images/class_share/share_bg.png', 0, 0, this.screenWidth, this.screenHeight);
						canvasBox.drawImage('/static/images/class_share/share_main_bg.png', 30, (this.screenHeight / 7), (this.screenWidth - 60), 500);

						// 标题
						canvasBox.setFontSize(30);
						canvasBox.setFillStyle('#0a0');
						canvasBox.setFontWeight && canvasBox.setFontWeight('bold');
						canvasBox.fillText(this.name + '邀请您参加', 45, (this.screenHeight / 5));
						canvasBox.drawImage('/static/images/class_share/star_icon.png', (this.screenWidth - 90), (this.screenHeight / 6), 48, 64);
						// 课程名
						canvasBox.setFontSize(18);
						canvasBox.setFillStyle('#010101');
						canvasBox.fillText(this.detailData.template.title, 45, (this.screenHeight / 4.1));

						//虚线
						canvasBox.lineWidth = 3;
						canvasBox.strokeStyle = '#000000';
						canvasBox.setLineDash([15, 5]);
						canvasBox.beginPath();
						canvasBox.moveTo(45, (this.screenHeight / 3.8));
						canvasBox.lineTo((this.screenWidth - 40), (this.screenHeight / 3.8));
						canvasBox.stroke();

						// 课程信息
						// canvasBox.setFontSize(14);
						// canvasBox.setFillStyle('#666666');
						// canvasBox.fillText('日期：' + this.detailData.source_data.course_time.start_date, 45,(this.screenHeight / 3.3));
						// canvasBox.fillText('时间：' + this.detailData.source_data.course_time.weekday + this.detailData.source_data.course_time.start_time + '~' + this.detailData.source_data.course_time.end_time, 45, (this.screenHeight / 3));
						// this.wrapText(canvasBox, this.detailData.source_data.location.address, 45, (this.screenHeight / 2.7), (this.screenWidth - 150), 24, 1);


						// 简介
						// const con = '通过本次课程，小朋友们将体验到足球的基本技巧，同时培养团队合作精神和运动兴趣。'
						// canvasBox.setFontSize(14);
						// this.wrapText(canvasBox, con, 45, (this.screenHeight / 2.3), (this.screenWidth - 150), 24, 2);
						//第二条虚线
						// canvasBox.lineWidth = 1;
						// canvasBox.strokeStyle = '#D2D2D2';
						// canvasBox.setLineDash([5, 5]);
						// canvasBox.beginPath();
						// canvasBox.moveTo(45, (imgHeight * 1.15));
						// canvasBox.lineTo((this.screenWidth - 40), (imgHeight * 1.15));
						// canvasBox.stroke();

						// 二维码（假设你有二维码图片地址）
						// canvasBox.drawImage(this.detailData.record.qrcode_url, 35, (this.screenHeight / 1.55), 75, 75);
						uni.getImageInfo({
							src: this.detailData.record.qrcode_url,
							success: (res) => {
								const qrImage  = this.detailData.record.qrcode_url;
								canvasBox.drawImage(qrImage, 45, (imgHeight * 1.2), 75, 75);
								// 调用draw方法进行绘图
								canvasBox.draw(false, () => {
									// 将绘制结果保存为图片
									uni.canvasToTempFilePath({
										canvasId: 'posterCanvas',
										success: res => {
											this.imageUrl = res.tempFilePath;
											// console.log('生成图片成功', this.imageUrl); // 调用微信内置的分享界面
										},
										fail: err => {
											console.log('生成图片失败', err);
										}
									}, this)
								});
							},
							fail: (err) => {
							  console.log(err);
							}
					  });
					  
					}
				})

			},
			// canvas文本换行
			wrapText(context, text, x, y, maxWidth, lineHeight, type) {
				// 字符分隔为数组
				const arrText = text.split('');
				let line = '';
				for (let n = 0; n < arrText.length; n++) {
					const testLine = line + arrText[n];
					const metrics = context.measureText(testLine);
					const testWidth = metrics.width;
					if (testWidth > maxWidth && n > 0) {
						if (n <= 18 && type == 1) {
							context.fillText('地址：' + line, x, y);
						} else if (n <= 18 && type == 2) {
							context.fillText('课程简介：' + line, x, y);
						} else context.fillText(line, x, y);
						line = arrText[n];
						y += lineHeight;
					} else {
						line = testLine;
					}
				}
				context.fillText(line, x, y);
			},

			choseShareWay(type) {
				if (type == 1) {
					this.savePoster();
				} else if (type == 2) {
					uni.share({
						provider: 'weixin',
						scene: 'WXSceneSession',
						type: 2,
						imageUrl: this.imageUrl,
						success: function(res) {
							console.log('success:' + JSON.stringify(res));
						},
						fail: function(err) {
							console.log('fail:' + JSON.stringify(err));
						}
					});
				} else if (type == 3) {
					uni.share({
						provider: 'weixin',
						scene: 'WXSceneTimeline',
						type: 3,
						imageUrl: this.imageUrl,
						success: function(res) {
							console.log('success:' + JSON.stringify(res));
						},
						fail: function(err) {
							console.log('fail:' + JSON.stringify(err));
						}
					});
				} else {
					this.copy();
				}
			},
			savePoster() {
				// console.log('图片链接',this.imageUrl)
				uni.saveImageToPhotosAlbum({
					filePath: this.imageUrl,
					success: () => {
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						});
					},
					fail: () => {
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						});
					}
				
				});
			},
			copy() {
				uni.showModal({
					content: this.imageUrl,
					confirmText: '复制内容',
					success: () => {
						uni.setClipboardData({
							data: this.imageUrl,
							success: function() {
								uni.hideToast({
									title: '复制成功',
									duration: 2000,
									icon: 'none'
								});
							},
							fail: function(err) {
								uni.showToast({
									title: '复制失败',
									duration: 2000,
									icon: 'none'
								});
							}
						});
					}
				});
			},
			shareToTimeline() {
				// 朋友圈分享需引导用户手动保存后到朋友圈发图
				uni.showModal({
					title: '提示',
					content: '请先保存图片，再到朋友圈分享',
					showCancel: false
				});
			}
		},
	};
</script>
<style lang="scss" scoped>
	.class_share {
		height: 100vh;
		// background-image: url("");
		// background-size: 100% 100%;
		// background-repeat: no-repeat;
		display: flex;
		justify-content: center;
		align-items: center;


		.share-popup {
			width: 100%;
			height: 100%;
			position: absolute;
			top: 0;
			bottom: 0;
			background-color: rgba(1, 1, 1, .7);
			z-index: 99;
		}

		.content {
			margin-bottom: 5vh;
			z-index: 999;
		}

		.main_content {
			// background-image: url("");
			// background-size: 100% 100%;
			// background-repeat: no-repeat;
			z-index: 999;
			width: 668rpx;
			height: 859rpx;
			padding: 50rpx;

			.main_info {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.left_info {
					.share_person {
						font-family: AlibabaPuHuiTi_3_115_Black;
						font-size: 60rpx;
						color: #05a110;
						line-height: 84rpx;
						font-weight: bold;
					}

					.class {
						font-family: PingFangSC, PingFang SC;
						font-weight: 500;
						font-size: 36rpx;
						color: #010101;
						line-height: 36rpx;
						padding: 39rpx 0 32rpx 0;
					}
				}

				.right_icon {
					width: 95.97rpx;
					height: 128rpx;
				}
			}
		}

		.line {
			height: 1rpx;
			border: 5rpx dashed #000000;
			border-spacing: 8rpx;
		}

		.class_info {
			.info {
				font-family: PingFangSC, PingFang SC;
				font-weight: 400;
				font-size: 28rpx;
				color: #666666;
				text-align: left;
				font-style: normal;
				padding-top: 30rpx;
			}

			.lh_48 {
				line-height: 48rpx;
			}
		}

		.code {
			width: 150rpx;
			height: 150rpx;
			background: red;
			margin-top: 40rpx;
		}

		.weixinBtn {
			width: 100%;
			position: absolute;
			left: 0;
			bottom: 5%;
			display: flex;
			justify-content: space-around;
			align-items: center;
		}

		.share_way_list {
			display: flex;
			justify-content: space-around;
			align-items: center;
			margin-top: 70rpx;
			z-index:999;
			

			.share_btn {
				padding: 0;
			}

			.share_way {
				text-align: center;

				.share_icon {
					width: 90rpx;
					height: 90rpx;
				}

				.share_tip {
					margin-top: 30rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 400;
					font-size: 24rpx;
					color: #ffffff;
					line-height: 24rpx;
				}
			}
		}
	}
</style>